package com.aacar.service.impl;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.aacar.dao.CouponDao;
import com.aacar.dao.OrderDao;
import com.aacar.dto.CouponDto;
import com.aacar.entity.Coupon;
import com.aacar.service.CouponService;
import com.aacar.vo.CommonVo;
import com.aacar.vo.CouponVo;
import com.google.common.collect.Maps;

@Repository("couponService")
public class CouponServiceImpl implements CouponService{
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private CouponDao couponDao;//优惠券号
	
	@Autowired
	private OrderDao orderDao;//订单dao
	
	static final String COUPON_FREE_FOR_1ST = "SDMF";

	@Override
	public Map<String,Object> validatorCoupon(CouponDto couponDto) {
		CommonVo cmv = new CommonVo();
		Coupon coupon = new Coupon();
		boolean is1stFree = false;
		Map<String,Object> map = Maps.newConcurrentMap();
		if (COUPON_FREE_FOR_1ST.equals(couponDto.getCouponNo())) {
			if (!COUPON_FREE_FOR_1ST.equals(couponDto.getCouponPassword())) {
				map.put("couponAmount","0");
				map.put("flag", "0");
				map.put("info", "优惠券不能使用,优惠券用户名和密码错误.");
				
				return map;
			} else {
				is1stFree = true;
			}
		}
		
		CouponVo cv = null;
		if (is1stFree) {
			cv = this.couponDao.validate1stAvailableCoupon();
		} else {
			coupon.setCouponNo(couponDto.getCouponNo());
			coupon.setCouponPassword(couponDto.getCouponPassword());
			cv = this.couponDao.validatorCoupon(coupon);
		}
//		coupon.setCouponNo(couponDto.getCouponNo());
//		coupon.setCouponPassword(couponDto.getCouponPassword());
//		CouponVo cv = this.couponDao.validatorCoupon(coupon);
//		Map<String,Object> map = Maps.newConcurrentMap();
		//根据用户id
		Map<String,Object> couponMap  = this.orderDao.findCouponByUserId(couponDto.getUserId());
		Map<String,Object> couponMap2 = this.orderDao.findCouponByCarNo(couponDto.getCarNo());
		logger.info("############ couponMap:"+couponMap);
		logger.info("############ couponMap2:"+couponMap2);
		if(null != couponMap) {
			map.put("couponAmount","0");
			map.put("flag", "0");
			map.put("info", "你已经使用过优惠券.");
			return map;
		}
		
		if(null != couponMap2) {
			map.put("couponAmount","0");
			map.put("flag", "0");
			map.put("info", "你已经使用过优惠券.");
			return map;
		}
		
		if(null != cv) {
			map.put("couponAmount", cv.getCouponAmount());
			map.put("flag", "1");
			map.put("info", "优惠券可以使用");
		} else {
			map.put("couponAmount","0");
			map.put("flag", "0");
			map.put("info", "优惠券不能使用,优惠券用户名和密码错误.");
		}
		
		return map;
	}
}
